import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

import '../api_client.dart';
import '../tools.dart';

class SignInCameraScreen extends StatefulWidget {
  final List<CameraDescription> cameras;

  const SignInCameraScreen({Key? key, required this.cameras}) : super(key: key);

  @override
  _SignInCameraScreenState createState() => _SignInCameraScreenState();
}

class _SignInCameraScreenState extends State<SignInCameraScreen> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    CameraDescription frontCamera = widget.cameras.firstWhere(
            (camera) => camera.lensDirection == CameraLensDirection.front,
        orElse: () => widget.cameras.first // 如果没有前置摄像头，使用第一个
    );
    _controller = CameraController(frontCamera, ResolutionPreset.medium);
    _initializeControllerFuture = _initializeController();
  }

  Future<void> _initializeController() async {
    try {
      await _controller.initialize();
    } catch (e) {
      print('摄像头控制器初始化失败: $e');
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> saveSignInTime() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    DateTime now = DateTime.now();
    await prefs.setString('lastSignInTime', now.toIso8601String());
    if (kDebugMode) {
      print('Sign-in time saved: $now');
    }
  }

  Future<void> _signIn() async {
    setState(() {
      _isLoading = true; // 开始加载时，设置为true
    });

    try {
      await _initializeControllerFuture;
      final image = await _controller.takePicture();
      File file = File(image.path);
      XFile? compressedFile = await _compressImage(file);
      if (compressedFile != null) {
        // 上传图片
        await _uploadImage(compressedFile);
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error: $e');
      }
    } finally {
      setState(() {
        _isLoading = false; // 无论成功或失败，结束加载时设置为false
      });
    }
  }

  Future<void> _createFace(String url) async {
    final formData = {
      'url': url
    };
    try {
      final response = await ApiClient.sendPostRequest('util/verifyFace', formData);
      if (response != null) {
        Map<String, dynamic> jsonMap = jsonDecode(response);
        bool success = jsonMap['success'];
        if (success) {
          saveSignInTime();
          final responseSignIn = await ApiClient.sendGetRequest('user/signIn');
          if (responseSignIn != null) {
            Map<String, dynamic> jsonMap = jsonDecode(response);
            bool success = jsonMap['success'];
            if (success) {
              _showSignInSuccessDialog();
            }
          }else {
            print(responseSignIn);
            _showSignInFalseDialog();
          }
        } else {
          _showSignInFalseDialog();
          if (kDebugMode) {
            print("Failed response: $response");
          }
        }
      } else {
        SnackbarHelper.showToast("请求失败，服务器错误，请联系系统管理员！");
        if (kDebugMode) {
          print("No response received");
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print("Exception: $e");
      }
    }
  }


  Future<XFile?> _compressImage(File file) async {
    final tempDir = await getTemporaryDirectory();
    final tempPath = tempDir.path;
    final result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      '$tempPath/img_${DateTime
          .now()
          .millisecondsSinceEpoch}.jpg',
      quality: 80,
    );
    return result;
  }

  Future<void> _uploadImage(XFile image) async {
    final prefs = await SharedPreferences.getInstance();
    final String? token = prefs.getString('userToken');
    Uri uri = Uri.parse("http://api.aiyuye.shop/util/uploadFace");
    var request = http.MultipartRequest('POST', uri)
      ..files.add(await http.MultipartFile.fromPath('file', image.path))
      ..headers.addAll({
        'token': token.toString()
      });
    try {
      var response = await request.send();
      final responseBody = await response.stream.bytesToString();
      if (response.statusCode == 200) {
        Map<String, dynamic> jsonMap = jsonDecode(responseBody);
        bool success = jsonMap['success'];
        if (success) {
          _createFace(jsonMap['msg']);
          if (kDebugMode) {
            print(responseBody);
          }
        } else {
          _showSignInFalseDialog();
          if (kDebugMode) {
            print("人脸上传失败");
            print(responseBody);
          }
        }
      } else {
        _showSignInFalseDialog();
        if (kDebugMode) {
          print("人脸上传失败");
          print(responseBody);
        }
      }
    } catch (error) {
      _showSignInFalseDialog();
      if (kDebugMode) {
        print("人脸上传失败");
        print('Error: $error');
      }
    }
  }



  void _showSignInSuccessDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('签到成功！'),
          content: Text('签到时间：${DateFormat('yyyy-MM-dd – kk:mm:ss').format(DateTime.now())}'),
          actions: <Widget>[
            TextButton(
              child: const Text('确定'),
              onPressed: () => _toFace(),
            ),
          ],
        );
      },
    );
  }


  void _showSignInFalseDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('签到失败！'),
          content: const Text('请重新签到！请保持人脸在画框中！'),
          actions: <Widget>[
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }


  Future<void> _toFace() async {
    if (mounted) {
      await _controller.dispose();
      Navigator.of(context).pushReplacementNamed('/main', arguments: 2);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('人脸签到'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => _toFace(),
        ),
        backgroundColor: Colors.blueGrey[900],
      ),
      body: Stack(
        children: [
          FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return snapshot.hasError
                    ? Center(
                      child: Text(
                      '摄像头预览失败: ${snapshot.error}',
                      style: const TextStyle(color: Colors.red),
                    ),
                )
                    : CameraPreview(_controller);
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
          if (_isLoading) // 如果正在加载，显示一个全屏的加载遮罩
            const Center(child: CircularProgressIndicator()),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(bottom: 50),
        child: SizedBox(
          height: 70,
          width: 70,
          child: FloatingActionButton(
            onPressed: _signIn,
            backgroundColor: _isLoading ? Colors.grey : Colors.green, // 如果正在加载，按钮显示为灰色
            child: const Icon(Icons.camera_alt, size: 28),
          ),
        ),
      ),
    );
  }

}

